<template>
  <el-dialog :model-value="visible" width="30%" :title="props.id ? '编辑角色' : '添加角色'" @close="close">
    <el-form :model="form" ref="formRef" :rules="rules" :label-width="120">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" />
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="form.roleDesc" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, reactive, getCurrentInstance } from 'vue';
import { addRoleApi, getRolesByIdApi, editRolesApi } from '@/api/authInterface';

const { proxy } = getCurrentInstance() as any

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  id: {
    type: Number,
    default: undefined
  }
})
const emits = defineEmits(['close'])

watch(() => props.visible, (newValue) => {
  if (newValue) {
    if (props.id) {
      getRolesByIdApi(props.id).then(res => {
        form.id = res.data.id
        form.roleName = res.data.roleName
        form.roleDesc = res.data.roleDesc
      })
    }
  }
})

const form = reactive({
  id: undefined,
  roleName: undefined,
  roleDesc: undefined
})
const rules = reactive({
  roleName: [
    { required: true, message: '角色名称是必填项', trigger: 'blur' }
  ],
  roleDesc: [
    { required: true, message: '角色描述是必填项', trigger: 'blur' }
  ]
})

const formRef = ref()

const submit = async () => {
  if (props.id) {
    editRolesApi(props.id, form).then(res => {
      proxy.$message.success(res.meta.msg)
      close()
    })
  } else {
    const res = await addRoleApi(form)
    if (res.meta.status === 201) {
      proxy.$message.success(res.meta.msg)
      close()
    }
  }
}

const close = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  emits('close')
}
</script>

<style scoped></style>